﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.ASPxEditors;
using EnterpriseFund.Common;
using DevExpress.Web.Mvc;
using System.Data;
using System.IO;
using Newtonsoft.Json;

namespace EnterpriseFund.Controllers
{
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class UpLevelAllowanceController : AdminBaseController
    {
        //
        // GET: /UpLevelAllowance/
        [AuthorityActionFilter("m_UpLevelAllowance", Order = 1)]
        [LogPageActionFilter("其他补助录入", Order = 2)]
        public ActionResult Index()
        {
            string strwhere = "1=1";
            List<Model.UpLevelAllowance> UpLevelAllowanceList = new List<Model.UpLevelAllowance>();
            UpLevelAllowanceList = GetUpLevelAllowanceListList(strwhere, 1);
            return View(UpLevelAllowanceList);
        }

        public ActionResult UpLevelAllowanceListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;

            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }
            string strwhere = "1=1";

            List<Model.UpLevelAllowance> UpLevelAllowanceList = new List<Model.UpLevelAllowance>();
            UpLevelAllowanceList = GetUpLevelAllowanceListList(strwhere, pageIndex);
            return PartialView("UpLevelAllowanceListPartial", UpLevelAllowanceList);
        }

        /// <summary>
        /// 获取定义的工作时间数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        /// <param name="pageIndex">第几页</param>
        /// <returns>查询出来的数据</returns>
        private List<Model.UpLevelAllowance> GetUpLevelAllowanceListList(string strWhere, int pageIndex)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.UpLevelAllowance UpLevelAllowanceBLL = new BLL.UpLevelAllowance();
            string fiedls = "FUpLevelAllowanceID";
            int total;
            DataSet ds = commonBll.GetListByPage("fund.v_UpLevelAllowance", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "FUpLevelAllowanceID", out total);
            List<Model.UpLevelAllowance> UpLevelAllowanceList = UpLevelAllowanceBLL.DataTableToList(ds.Tables[0]);
            List<Model.UpLevelAllowance> UpLevelAllowanceAllList = new List<Model.UpLevelAllowance>();
            total = UpLevelAllowanceBLL.GetRecordCount2(strWhere);
            int pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                UpLevelAllowanceAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (UpLevelAllowanceList.Count > i)
                {
                    UpLevelAllowanceAllList[((pageIndex - 1) * pageRowSize) + i] = UpLevelAllowanceList[i];
                }
            }

            return UpLevelAllowanceAllList;
        }

        public DataTable GetShowData(DataTable dt)
        {
            dt.Columns.Add("cz");
            foreach (DataRow drz in dt.Rows)
            {
                drz["cz"] = "mx";
                drz["FUpLevelAmount"] = decimal.Parse(drz["FUpLevelAmount"].ToString()) ;
            }
            dt.Columns["FUpLevelAmount"].DataType = typeof(decimal);
            decimal sumse = dt.AsEnumerable().Sum(p => p.Field<decimal>("FUpLevelAmount")) + dt.AsEnumerable().Sum(p => p.Field<decimal>("FLocalAmount"));
            DataRow dr = dt.NewRow();
            dr["cz"] = "合计";
            dr["FUpLevelAmount"] = sumse;
            dt.Rows.Add(dr);
            return dt;
        }

        public ActionResult Import()
        {
            var uploadFiles = UploadControlExtension.GetUploadedFiles("upload");
            if (null == uploadFiles || uploadFiles.Length == 0)
            {

                return View();
            }
            else
            {
                var msg = SaveYGZExcel();
                ViewBag.Msg = msg;
                return View();
            }
        }
        public string SaveYGZExcel()
        {
            var ErrMsg = "";
            try
            {
                //上传
                var uploadFiles = UploadControlExtension.GetUploadedFiles("upload");
                if (null == uploadFiles || uploadFiles.Length == 0)
                {
                    ErrMsg = "请选择Excel文件！";
                    return ErrMsg;
                }
                var upload = uploadFiles[0];
                var clintFileName = upload.FileName;
                var extName = clintFileName.Substring(clintFileName.LastIndexOf('.') + 1);
                var svrFileName = string.Format("{0}.{1}", DateTime.Now.ToString("yyyyMMddHHmm"), extName);
               // var uploadoffiepath = string.Format("~/Publish/{0}/QTBZ/{1}{2}/", GlobalConstant.ENTITYNO, DateTime.Now.Year, DateTime.Now.Month);
                var uploadoffiepath = Server.MapPath(Url.Content("~") + string.Format("/Publish/{0}/QTBZ/{1}{2}/", GlobalConstant.ENTITYNO, DateTime.Now.Year, DateTime.Now.Month));
                if (!Directory.Exists(uploadoffiepath))//如果不存在就创建
                {
                    Directory.CreateDirectory(uploadoffiepath);
                }
                upload.SaveAs(uploadoffiepath + svrFileName);

                //读取
                var dt = new BLL.SB_ZSXX().ReadExcelTitle(uploadoffiepath + svrFileName).Tables[0];

                //验证
                var cols = new List<string> { "纳税人名称", "补助金额", "地方配套", "备注" };
                foreach (var col in cols)
                {
                    if (!dt.Columns.Contains(col))
                    {
                        ErrMsg = "Excel文件格式错误！";
                        return ErrMsg;
                    }
                }
                BLL.UpLevelAllowanceEntry upLevelAllowanceEntryBLL = new BLL.UpLevelAllowanceEntry();
                Model.UpLevelAllowance modela = new Model.UpLevelAllowance();
                BLL.UpLevelAllowance upLevelAllowanceBLL = new BLL.UpLevelAllowance();
                string FUpLevelAllowanceID = Session["FUpLevelAllowanceID"] as string;
                //   DataTable dts = upLevelAllowanceEntryBLL.GetList(" FUpLevelAllowanceID = '" + FUpLevelAllowanceID + "'").Tables[0];
                modela = upLevelAllowanceBLL.GetModel(FUpLevelAllowanceID);
                List<Model.UpLevelAllowanceEntry> upLevelAllowanceEntryList = new List<Model.UpLevelAllowanceEntry>();
                var models = new List<Model.YGZAllowance>();
                DataTable dts = new DataTable();
                dts.Columns.Add("NSRDZDAH");
                dts.Columns.Add("NSRMC");
                dts.Columns.Add("FUpLevelAmount");
                dts.Columns.Add("FLocalAmount");
                dts.Columns.Add("FNote");
                for (var i = 0; i < dt.Rows.Count; i++)
                {
                    var r = dt.Rows[i];
                    var excelRowIndex = i + 2;



                    if (r.IsNull("纳税人名称") || string.IsNullOrEmpty(r["纳税人名称"].ToString()))
                    {
                        ErrMsg = "Excel文件第" + excelRowIndex + "行，纳税人名称不能为空！";
                        return ErrMsg;
                    }

                    var amount = 0m;
                    if (!decimal.TryParse(r["补助金额"].ToString(), out amount))
                    {
                        ErrMsg = "Excel文件第" + excelRowIndex + "行，金额数据有误！";
                        return ErrMsg;
                    }
                    if (r["地方配套"].ToString() != "")
                    {
                        if (!decimal.TryParse(r["地方配套"].ToString(), out amount))
                        {
                            ErrMsg = "Excel文件第" + excelRowIndex + "行，地方配套金额数据有误！";
                            return ErrMsg;
                        }
                    }
                    else
                    {
                        r["地方配套"] = 0;
                    }

                    var nsr = new BLL.DJ_NSRXX().GetList(1, string.Format("[NSRMC] = '{0}'", r["纳税人名称"]), "NSRMC").Tables[0];
                    if (nsr.Rows.Count == 0)
                    {
                        ErrMsg = "Excel文件第" + excelRowIndex + "行，该纳税人不存在！";
                        return ErrMsg;
                    }

                    var NSRDZDAH = decimal.Parse(nsr.Rows[0]["NSRDZDAH"].ToString());

                    BLL.UpLevelAllowanceEntry b = new BLL.UpLevelAllowanceEntry();

                    DataRow dr = dts.NewRow();
                    //dr["FUpLevelAllowanceEntryID"] = "";
                    //dr["FUpLevelAllowanceID"] =string.IsNullOrEmpty(FUpLevelAllowanceID)?"": FUpLevelAllowanceID;
                    dr["NSRDZDAH"] = NSRDZDAH;
                    dr["NSRMC"] = r["纳税人名称"];
                    dr["FUpLevelAmount"] = decimal.Parse(r["补助金额"].ToString())*10000;
                    dr["FLocalAmount"] = decimal.Parse(r["地方配套"].ToString());
                    dr["FNote"] = string.IsNullOrEmpty(r["备注"].ToString()) ? "" : r["备注"].ToString();


                    //var model = new Model.UpLevelAllowanceEntry();

                    //model.FUpLevelAllowanceID = FUpLevelAllowanceID;
                    //model.FUpLevelAmount = decimal.Parse(r["补助金额"].ToString());
                    //model.FLocalAmount = decimal.Parse(r["地方配套"].ToString());
                    //model.NSRDZDAH = NSRDZDAH;
                    //model.FNote = r["备注"].ToString();
                    //model.FExcelFileName = svrFileName;
                    //model.FExcelRowNumber = excelRowIndex;
                    //model.FEntityNo = GlobalConstant.ENTITYNO;
                    //model.FInsDate = DateTime.Now;
                    //model.FInsDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                    //model.FInsEmpNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    //model.FInsIP = GenerateUtil.GetClientIPv4Address();
                    //model.FUpdDate = model.FInsDate;
                    //model.FUpdDeptNo = model.FInsDeptNo;
                    //model.FUpdEmplNo = model.FUpdEmplNo;
                    //model.FUpdIP = model.FInsIP;
                    // upLevelAllowanceEntryList.Add(model);
                    dts.Rows.Add(dr);
                }

                //   upLevelAllowanceBLL.Update2(upLevelAllowanceEntryList, modela);
                Session["foradddata"] = dts;
                return "ok";

            }
            catch (System.Exception ex)
            {
                return "error" + ex.Message.ToString() + ErrMsg;
            }
            //保存

            //  var isSuccess = _bll.AddList(models);
           // return "ok";
        }

        public ActionResult Save(Model.UpLevelAllowance upLevelAllowanceModel)
        {
            string FUpLevelAllowanceID = Fetch.Post("hidFUpLevelAllowanceID");
            string nsdzdanList = Fetch.Post("hidNSRDZDAH");
            try
            {
                List<Model.UpLevelAllowanceEntry> upLevelAllowanceEntryList = new List<Model.UpLevelAllowanceEntry>();

                string[] noList = nsdzdanList.Split(',');
                foreach (string n in noList)
                {
                    if (n != "")
                    {
                        Model.UpLevelAllowanceEntry model = new Model.UpLevelAllowanceEntry();
                        model.FUpLevelAmount = decimal.Parse(Fetch.Post("hid" + n + "FUpLevelAmount"));
                        model.NSRDZDAH = decimal.Parse(n);
                        model.FLocalAmount = decimal.Parse(Fetch.Post("hid" + n + "FLocalAmount"));
                        model.FNote = Fetch.Post("hid" + n + "FNote");
                        upLevelAllowanceEntryList.Add(model);
                    }
                }
                BLL.UpLevelAllowanceCls UpLevelAllowanceClsBLL = new BLL.UpLevelAllowanceCls();
                Model.UpLevelAllowanceCls clsModel = new Model.UpLevelAllowanceCls();
                upLevelAllowanceModel.FUpLevelAllowanceID = FUpLevelAllowanceID;
                upLevelAllowanceModel.FEntityNo = GlobalConstant.ENTITYNO;
                //upLevelAllowanceModel.FFileName = Fetch.Post("");
                //upLevelAllowanceModel.FFileNo = Fetch.Post("");
                upLevelAllowanceModel.FFileTransDate = DateTime.Now;
                //upLevelAllowanceModel.FFinancePropNo = Fetch.Post("");
                upLevelAllowanceModel.FInsDate = DateTime.Now;
                upLevelAllowanceModel.FInsDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                upLevelAllowanceModel.FInsEmpNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                upLevelAllowanceModel.FInsIP = GenerateUtil.GetClientIPv4Address();
                //upLevelAllowanceModel.FUpLevelAllowanceClsNo = Fetch.Post("");
                clsModel = UpLevelAllowanceClsBLL.GetModel(upLevelAllowanceModel.FUpLevelAllowanceClsNo);
                if (clsModel.FIsAudit == "Y")
                {
                    upLevelAllowanceModel.FIsAudit = "Y";
                    upLevelAllowanceModel.FIsReturn = "N";
                    upLevelAllowanceModel.FStatus = "N";
                }
                else
                {
                    upLevelAllowanceModel.FIsAudit = "N";
                    upLevelAllowanceModel.FIsReturn = "N";
                    upLevelAllowanceModel.FStatus = "A";
                }
                upLevelAllowanceModel.FYear = decimal.Parse(OperateSession.get(GlobalConstant.PARAM_SYSYEAR));

                BLL.UpLevelAllowance upLevelAllowanceBLL = new BLL.UpLevelAllowance();
                if (FUpLevelAllowanceID != null && FUpLevelAllowanceID != "")
                {
                    upLevelAllowanceBLL.Update(upLevelAllowanceEntryList, upLevelAllowanceModel);
                }
                else
                {
                    upLevelAllowanceBLL.Add(upLevelAllowanceEntryList, upLevelAllowanceModel);
                }

                ViewData["jsAlert"] = "操作成功";
            }
            catch (Exception ex)
            {
                ViewData["jsAlert"] = ex.Message;
            }
            return UpLevelAllowanceEdit(FUpLevelAllowanceID);
        }
        public string GetAdddata(string pdata)
        {
            if (pdata != "" & pdata != null)
            {

                string[] noList = pdata.Split(',').Distinct().ToArray();
                DataTable dts = Session["foradddata"] as DataTable;
                string str = "";
                foreach (string n in noList)
                {
                    if (dts.Select("NSRDZDAH=" + n).Count() > 0)
                    {

                        str += dts.Select("NSRDZDAH=" + n)[0]["NSRMC"].ToString()+";";
                    }
                }
                if (str != "")
                {
                    return "error|您所导入的企业有重复项目:" + str;
                }
                else
                {
                     return     JsonConvert.SerializeObject(Session["foradddata"]);
                }
            }
             return     JsonConvert.SerializeObject(Session["foradddata"]);
           // return Json(Session["foradddata"]);
        }
        public ActionResult UpLevelAllowanceEdit(string FUpLevelAllowanceID)
        {
            BLL.UpLevelAllowance upLevelAllowanceBLL = new BLL.UpLevelAllowance();
            BLL.UpLevelAllowanceEntry upLevelAllowanceEntryBLL = new BLL.UpLevelAllowanceEntry();
            Model.UpLevelAllowance model = new Model.UpLevelAllowance();
            BLL.UpLevelAllowanceCls upLevelAllowanceClsBLL = new BLL.UpLevelAllowanceCls();
            ViewData["UpLevelAllowanceClsList"] = upLevelAllowanceClsBLL.GetModelList("");
            if (FUpLevelAllowanceID != null && FUpLevelAllowanceID != "")
            {
                model = upLevelAllowanceBLL.GetModel(FUpLevelAllowanceID);
            }
            DataTable dt = upLevelAllowanceEntryBLL.GetList(" FUpLevelAllowanceID = '" + FUpLevelAllowanceID + "'").Tables[0];
           // Session["preshowdata"] = dt;
            //foreach (DataRow r in (Session["foradddata"] as DataTable).Rows)
            //{
            //    dt.Rows.Add(r); 
            //}
                //  Session["showdata"] = GetShowData(dt);
            Session["foradddata"] = null;
            ViewData["showdata"] = GetShowData(dt);
            ViewData["FUpLevelAllowanceID"] = FUpLevelAllowanceID;
            Session["FUpLevelAllowanceID"] = FUpLevelAllowanceID;
            BLL.FinanceProp FinancePropBLL = new BLL.FinanceProp();
            ViewData["FinancePropList"] = FinancePropBLL.GetModelList("");
            return View("UpLevelAllowanceEdit", model);
        }

        public ActionResult TaxPayerAdd()
        {
            return View();
        }

        public ActionResult LargeDataComboBoxPartial()
        {
            return PartialView();
        }

        public string DelUpLevelAllowance(string FUpLevelAllowanceID)
        {
            string str = string.Empty;
            if (null != FUpLevelAllowanceID)
            {
                FUpLevelAllowanceID = Fetch.estimateString(FUpLevelAllowanceID, CheckGetEnum.Safety);
                BLL.UpLevelAllowance codeNameBll = new BLL.UpLevelAllowance();
                try
                {
                    codeNameBll.Delete(FUpLevelAllowanceID);
                    str = "ok";
                }
                catch (Exception)
                {
                    str = "error";
                }
            }
            return str;
        }

    }
}
